package onlinediary.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import onlinediary.entity.Diary;
import onlinediary.entity.Group;
import onlinediary.entity.User;
import onlinediary.service.IGroupService;
import onlinediary.utils.R;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author
 * @since 2022-05-03
 */
@CrossOrigin
@Controller
@RequestMapping("/group")
public class GroupController {

    @Resource
    private IGroupService groupService;

    @GetMapping("/groupDetail")
    public String groupDetail(Model model, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        List<Group> groupList = groupService.list(
                new QueryWrapper<Group>()
                        .lambda()
                        .eq(Group::getUId, user.getId())
        );
        model.addAttribute("groupList", groupList);
        return "diaryGroup";
    }

    @GetMapping("/delete")
    @ResponseBody
    public R delete(Integer id) {
        Group group = groupService.getById(id);
        Integer dcount = group.getDcount();
        if (dcount > 0) {
            return R.error(5000, "删除失败！请先删除该组下的所有日记！");
        } else {
            groupService.removeById(id);
            return R.ok("删除成功！");
        }
    }

    @GetMapping("/updatePage")
    public String updatePage(Integer id, Model model) {
        Group group = groupService.getById(id);
        model.addAttribute("group", group);
        return "addMessage/addDiaryGroup";
    }

    @PostMapping("/update")
    public String update(Group group) {
        groupService.updateById(group);
        return "redirect:/group/groupDetail";
    }

    @GetMapping("/insertPage")
    public String insertPage() {
        return "addMessage/insertDiaryGroup";
    }

    @PostMapping("/insert")
    public String insert(Group group,HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        group.setDcount(0);//日记个数默认为0
        group.setUId(user.getId());
        groupService.save(group);
        return "redirect:/group/groupDetail";
    }
}
